﻿using System;
using System.Configuration;
using System.Data;
using System.Collections;
using System.IO;
using System.Text;
using System.Web;


namespace Token.Util
{
    /// <summary>
    ///  上传下载文件时用到的静态方法
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 上传根路径
        /// </summary>
        public static string UPLOAD_ROOT = "~/uploads/";

        /// <summary>
        /// 上传临时路径
        /// </summary>
        public static string UPLOAD_TMP_PATH = UPLOAD_ROOT + "~/temp/";

        /// <summary>
        /// 获取当天保存文件的文件夹路径
        /// 若无该文件夹，则新建
        /// </summary>
        /// <returns>
        /// 返回新建的文件夹路径，末尾有 "/"
        /// </returns>
        public static String GetUploadPathToday() 
        {
            StringBuilder path = new StringBuilder( UPLOAD_ROOT);
            path.Append(DateTime.Now.ToString("yyyy-MM-dd"));
            String absolutePath = System.Web.HttpContext.Current.Request.MapPath(path.ToString());
            DirectoryInfo dir = new DirectoryInfo(absolutePath);
            try
            {
                if (!dir.Exists)
                {

                    dir.Create();
                }
            }
            catch (Exception e)
            {
                LogHelper.Error("新建文件: " + path.ToString() + "时出错！", e);
            }
           
            return path.Append("/").ToString();
        }

        /// <summary>
        /// 生成文件的随机名称
        /// 生成的文件形式为： 原文件名前10个字符 + _ + DateTime.Now.ToFileTime().ToString()
        /// 若原文件名不足10个字符，不会补充
        /// </summary>
        /// <param name="name">原文件名，不包括文件扩展名</param>
        /// <returns>   
        /// 返回生成的文件名，若失败，则返回 null
        /// </returns>
        public static String GenerateFileRandomName(String name)
        {
            if (String.IsNullOrEmpty(name)) 
            {
                LogHelper.Error("输入文件名无内容！" + name, null);
                return null;
            }

            if (name.LastIndexOf("\\") > 0)
            {
                name = name.Substring(name.LastIndexOf(@"\") + 1 , name.Length - name.LastIndexOf("\\") - 1);
            }

            if (name.Length > 10) 
            {
                name = name.Substring(0, 10);
            }
            String fileName = null;
           
            lock (UPLOAD_ROOT)
            {
                int random = new Random().Next(1000);
                fileName = name + "_" + DateTime.Now.ToFileTime().ToString() + random;
            }
            return fileName;
        }

    }
}